package com.example.mood;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Mapa extends Activity implements OnClickListener {
	// Google Map
	private GoogleMap googleMap;
	private Button volver;
	private ArrayList<Estado> datos;
	private ProgressDialog pDialog;

	private HashMap<String, String> user;
	SessionManager session;
	JSONParser jsonParser = new JSONParser();

	private static final String ESTADOS_URL = "http://www.moodapp.es//webservice/cargarEstados.php";
	private static final String TAG_USERNAME = "username";
	private static final String TAG_MENSAJE = "mensaje";
	private static final String TAG_UBICACION = "localizacion";
	private static final String TAG_POSTS = "posts";
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_ESTADO = "estado";
	private static final String TAG_ID_USUARIO = "idUsuario";
	private static final String TAG_NIVEL = "nivel";
	private static final String TAG_LOCATION = "localizacion";
	private static final String TAG_FECHA = "fecha";
	private static final String TAG_ID = "id";

	// organiza los estados en una lista.
	private ArrayList<HashMap<String, String>> mEstadosList;
	// array con los amigos
	private JSONArray mEstados = null;
    ImageLoader imageLoader;
	private DisplayImageOptions options;
	private Hashtable<String, String> markers;
	



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mapa);
		ActionBar ab = getActionBar();
		ab.setTitle("Mood");
		volver = (Button) this.findViewById(R.id.btnVerEnLista);
		volver.setOnClickListener(this);
        markers = new Hashtable<String, String>();
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.perfildefecto)		//	Display Stub Image
		.showImageForEmptyUri(R.drawable.perfildefecto)	//	If Empty image found
		.cacheInMemory()
		.cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();
		initilizeMap();
		



	}

	private void mostrarArrayList() {
		// TODO Auto-generated method stub
		for (int i = 0; i < datos.size(); i++) {
			System.out.println(datos.get(i).getEstado());
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		new buscarEstados().execute();
		//cargarMapa2();

	}

	/**
	 * function to load map If map is not created it will create it for you
	 * */
	private void initilizeMap() {
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(getApplicationContext(),
						"Sorry! unable to create maps", Toast.LENGTH_SHORT)
						.show();
			}
		}
		if(googleMap!=null){
                googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
                {
                    @Override
                    public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker)
                    {
                        marker.showInfoWindow();
                        return true;
                    }
                });
            }
	}

	private void cargarMapa2() {
		try {
			// Changing map type
			
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

			// Showing / hiding your current location
			googleMap.setMyLocationEnabled(true);

			// Enable / Disable zooming controls
			googleMap.getUiSettings().setZoomControlsEnabled(false);

			// Enable / Disable my location button
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);

			// Enable / Disable Compass icon
			googleMap.getUiSettings().setCompassEnabled(true);

			// Enable / Disable Rotate gesture
			googleMap.getUiSettings().setRotateGesturesEnabled(true);

			// Enable / Disable zooming functionality
			googleMap.getUiSettings().setZoomGesturesEnabled(true);
			
			
			// 36.850986,-2.456277
			double latitude, longitude;
			// Vamos a poner bolitas de estado.
			for (int i = 0; i < datos.size(); i++) {
				// random latitude and logitude

				longitude = cargarLongitud(datos.get(i).getLocalizacion());
				latitude = cargarLatitud(datos.get(i).getLocalizacion());

				// Adding a marker
				MarkerOptions marker = new MarkerOptions().position(
						new LatLng(latitude, longitude)).title(datos.get(i).getNick() + datos.get(i).getEstado()).snippet(
								datos.get(i).getMensaje());
				markers.put(marker.getTitle(), datos.get(i).getNick());
				

				//Log.e("Random", "> " + latitude + ", " + longitude);
				if (Integer.parseInt(datos.get(i).getNivel()) < 20) {
					marker.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.imuytriste));//
				} else if (Integer.parseInt(datos.get(i).getNivel()) > 19
						&& Integer.parseInt(datos.get(i).getNivel()) < 50) {
					marker.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.itriste));
				} else if (Integer.parseInt(datos.get(i).getNivel()) > 49
						&& Integer.parseInt(datos.get(i).getNivel()) < 80) {
					marker.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.ifeliz));
				} else if (Integer.parseInt(datos.get(i).getNivel()) > 79) { 
					marker.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.imuyfeliz));

				}

				
				googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
				googleMap.addMarker(marker);

				CameraPosition cameraPosition = new CameraPosition.Builder()
						.target(new LatLng(latitude, longitude)).zoom(15)
						.build();

				googleMap.animateCamera(CameraUpdateFactory
						.newCameraPosition(cameraPosition));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void cargarMapa() {
		try {
			// Loading map
			initilizeMap();

			// Changing map type
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
			// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

			// Showing / hiding your current location
			googleMap.setMyLocationEnabled(true);

			// Enable / Disable zooming controls
			googleMap.getUiSettings().setZoomControlsEnabled(false);

			// Enable / Disable my location button
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);

			// Enable / Disable Compass icon
			googleMap.getUiSettings().setCompassEnabled(true);

			// Enable / Disable Rotate gesture
			googleMap.getUiSettings().setRotateGesturesEnabled(true);

			// Enable / Disable zooming functionality
			googleMap.getUiSettings().setZoomGesturesEnabled(true);
			// 36.850986,-2.456277
			double latitude = 36.850986;
			double longitude = -2.456277;

			// lets place some 10 random markers
			for (int i = 0; i < 10; i++) {
				// random latitude and logitude
				double[] randomLocation = createRandLocation(latitude,
						longitude);

				// Adding a marker
				MarkerOptions marker = new MarkerOptions().position(
						new LatLng(randomLocation[0], randomLocation[1]))
						.title("Hello Maps " + i);

				Log.e("Random", "> " + randomLocation[0] + ", "
						+ randomLocation[1]);

				// changing marker color
				if (i == 0)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
				if (i == 1)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
				if (i == 2)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
				if (i == 3)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
				if (i == 4)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
				if (i == 5)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
				if (i == 6)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_RED));
				if (i == 7)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
				if (i == 8)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
				if (i == 9)
					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

				googleMap.addMarker(marker);

				// Move the camera to last position with a zoom level
				if (i == 9) {
					CameraPosition cameraPosition = new CameraPosition.Builder()
							.target(new LatLng(randomLocation[0],
									randomLocation[1])).zoom(15).build();

					googleMap.animateCamera(CameraUpdateFactory
							.newCameraPosition(cameraPosition));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private double cargarLatitud(String localizacion) {
		StringTokenizer st = new StringTokenizer(localizacion, ",");
		return Double.parseDouble(st.nextToken());
	}

	private double cargarLongitud(String localizacion) {
		StringTokenizer st = new StringTokenizer(localizacion, ",");
		st.nextToken();
		return Double.parseDouble(st.nextToken()); //.replace(",", ".")
	}

	/*
	 * creating random postion around a location for testing purpose only Me
	 * vale para mi idea de que la posicion no sea la exacta
	 */
	private double[] createRandLocation(double latitude, double longitude) {

		return new double[] { latitude + ((Math.random() - 0.5) / 500),
				longitude + ((Math.random() - 0.5) / 500),
				150 + ((Math.random() - 0.5) * 10) };
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == volver.getId()) {
			finish();
		}

	}

	public void updateJSONdata() {

		// Session class instance
		session = new SessionManager(getApplicationContext());
		// get user data from session
		user = session.getUserDetails();
		String username = user.get(SessionManager.KEY_USERNAME);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username));
		mEstadosList = new ArrayList<HashMap<String, String>>();

		JSONObject json = jsonParser.makeHttpRequest(ESTADOS_URL, "POST",
				params);

		// cuando parseamos JSON es conveniente hacer un catch de las
		// excepciones

		try {

			// I know I said we would check if "Posts were Avail." (success==1)

			mEstados = json.getJSONArray(TAG_POSTS);

			// looping through all posts according to the json object returned
			for (int i = 0; i < mEstados.length(); i++) {
				JSONObject c = mEstados.getJSONObject(i);

				// gets the content of each tag
				String estado = c.getString(TAG_ESTADO);
				String location = c.getString(TAG_LOCATION);
				String nivel = c.getString(TAG_NIVEL);
				String fecha = c.getString(TAG_FECHA);
				String mensaje = c.getString(TAG_MENSAJE);
				String usern = c.getString(TAG_USERNAME);
				String id = c.getString(TAG_ID);

				// creating new HashMap
				HashMap<String, String> map = new HashMap<String, String>();

				map.put(TAG_NIVEL, nivel);
				map.put(TAG_FECHA, fecha);
				map.put(TAG_MENSAJE, mensaje);
				map.put(TAG_ESTADO, " se siente " + estado);
				map.put(TAG_LOCATION, location);
				map.put(TAG_ID, id);
				map.put(TAG_USERNAME, usern);

				// adding HashList to ArrayList
				mEstadosList.add(map);

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public class buscarEstados extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getApplicationContext());
			pDialog.setMessage("Cargando amigos...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
		}

		@Override
		protected Boolean doInBackground(Void... arg0) {
			updateJSONdata();
			return null;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			updateList();
			cargarMapa2();

		}
	}

	private void updateList() {

		datos = new ArrayList<Estado>();

		rellenarArrayList();

	}

	private void rellenarArrayList() {
		// TODO Auto-generated method stub
		for (int i = 0; i < mEstadosList.size(); i++) {
			Estado e = new Estado(mEstadosList.get(i).get(TAG_USERNAME),
					mEstadosList.get(i).get(TAG_MENSAJE), mEstadosList.get(i)
							.get(TAG_UBICACION), mEstadosList.get(i).get(
							TAG_NIVEL), mEstadosList.get(i).get(TAG_ESTADO));
			datos.add(e);
		}
		//cargarMapa();

	}
	public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter
	{
	    public MarkerInfoWindowAdapter()
	    {
	    }

	    @Override
	    public View getInfoWindow(Marker marker)
	    {
	        return null;
	    }

	    @Override
	    public View getInfoContents(final Marker marker)
	    {
	        View v  = getLayoutInflater().inflate(R.layout.infowindow_layout, null);

	        ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);

	        TextView markerLabel = (TextView)v.findViewById(R.id.marker_label);

	        String url = null;

				if (markers.get(marker.getTitle())!=null) {
					url = "http://www.moodapp.es/webservice/uploads/"+markers.get(marker.getTitle())+".jpg";
				}

			if (url != null && !url.equalsIgnoreCase("null")
					&& !url.equalsIgnoreCase("")) {
				imageLoader.displayImage(url, markerIcon, options,
						new SimpleImageLoadingListener() {
							@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
								super.onLoadingComplete(imageUri, view,
										loadedImage);
							}
						});
			} else {
				markerIcon.setImageResource(R.drawable.perfildefecto);
			}
	        markerLabel.setText(marker.getTitle());
	        
	        TextView anotherLabel = (TextView)v.findViewById(R.id.another_label);
	        anotherLabel.setText(marker.getSnippet());

	        return v;
	    }
	}

}